#!/usr/bin/env python
# encoding: utf-8

"""
    - 日志生成格式
        - 生成的日志放在路径 /home/admin/applogs/ 下
        - 日志名格式为:  app.log.20101210, app.log.20101211, etc.
            - 当天的日志也要有日期后缀, 目前 logspider 是按这种规则生成日志的.
        - 文件中的每一行格式是:
          序列号 时间戳 ip 应用名 中文
          样例行:
          1 2010-12-10 10:16:01.123 10.232.35.65 consign 测试乱码
"""
import os, sys
from threading import Thread, RLock
from time import sleep
import datetime

log_path = "./applogs/"
file_name_prefix = "app.log."
lock = RLock()

if not os.path.isdir(log_path): os.makedirs(log_path)


def open_file(suffix, log_path, file_name_prefix):
    """
            产生新文件
    """
    name = os.path.join(log_path, file_name_prefix) + suffix
    return open(name, "ab")


def file_rolling_checker(*a):
    control = a[0]
    while 1:
        try:
            lock.acquire()
            n = datetime.datetime.now()
            suffix = n.strftime("%Y%m%d")
            f = control['file'][1]
            if not f:
                file_for_write = open_file(suffix, control['log_path'], control['file_name_prefix'])
                #记录文件变量
                control['file'] = (suffix, file_for_write)
            else:
                if suffix not in control['file'][0]:
                    print "rolling file for", suffix
                    file_for_write = open_file(suffix, control['log_path'], control['file_name_prefix'])
                    #关闭上一天的文件
                    control['file'][1].close()
        
                    #记录文件变量
                    control['file'] = (suffix, file_for_write)
        finally:
            lock.release()

        #sleep 20 sec.
        sleep(20)

control = {"file":("", None), "file_name_prefix":file_name_prefix, "log_path":log_path}

t = Thread(target=file_rolling_checker, args=(control,))
t.daemon = True
t.start()

ip, appname = sys.argv[1:3]

seq = 0
while 1:
    try:
        lock.acquire()
        f = control['file'][1]
        if f:
            seq += 1
            n = datetime.datetime.now()
            cur = n.strftime("%Y-%m-%d %H:%M:%S.")
            f.write("%s %s%s %s %s 测试乱码\n" % (seq, cur, str(n.microsecond)[:3], ip, appname))
            if not seq % 10:
                f.flush()
    finally:
        lock.release()
    sleep(0.3)
